package cn.zl.netty.work;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Scanner;

/**
 * @Description:聊天客户端
 * @Author: zllwsy
 * @Date: 2020/10/29 9:55
 */
public class MyChatClient {
    public static void main(String[] args) {
        //1.创建一个线程组
        EventLoopGroup loopGroup = new NioEventLoopGroup();
        //2.创建客户端启动助手，完成相关配置
        Bootstrap bootstrap = new Bootstrap()
                //3.设置线程组
                .group(loopGroup)
                //4.设置客户端通道的实现类
                .channel(NioSocketChannel.class)
                //5.创建一个初始化通道对象 ，//步骤6在MyChatClientInitializer中
                .handler(new MyChatClientInitializer());

        try {
            System.out.println("Client is ready ...");
            //7.启动客户端去连接服务器端，connect方法是异步的，sync方法是同步阻塞的
            ChannelFuture future = bootstrap.connect("127.0.0.1", 52002).sync();
            Channel channel = future.channel();

            //8.手动在控制台输入内容，然后enter发送
            Scanner scanner = new Scanner(System.in);
            System.out.println("please enter ...");
            while (true) {
                String msg = scanner.nextLine();
                if ("exit".equals(msg)) break;
                System.out.println("msg is push ...");
                channel.writeAndFlush(msg + System.lineSeparator());
            }
            channel.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //9.关闭连接
            loopGroup.shutdownGracefully();
            System.out.println("Client is end ...");
        }

    }
}
